<template>
  <div class="home">
    <Header
      :data="exportChartData"
      @update-choose-month="handleUpdate"
      @update-choose-video="handleUpdateVideo"
      @reset="reset"
    ></Header>
    <div class="homeMain">
      <div class="left">
        <div class="top">
          <Title :title="'集热管破损'"></Title>
          <SingleBar :data="chartData1"></SingleBar>
        </div>
        <div class="middle">
          <Title :title="'外镜破损'"></Title>
          <SingleBar :data="chartData2"></SingleBar>
        </div>
        <div class="bottom">
          <Title :title="'内镜破损'"></Title>
          <SingleBar :data="chartData3"></SingleBar>
        </div>
      </div>
      <div class="center">
        <div class="centerBox">
          <div class="centerVideo">
            <video width="100%" height="100%" autoplay controls :src="videoUrl"></video>
          </div>
          <div class="statistics" @click="handleClick">
            <StatisticsData :data="StatisticDatas" />
          </div>
        </div>
        <div class="centerBottom">
          <Title :title="'历史曲线'"></Title>
          <div class="historyMonths">
            <el-date-picker
              v-model="chooseMonth"
              type="monthrange"
              unlink-panels
              range-separator="至"
              :disabled-date="disabledDate"
              @change="historyChange"
            />
            <span @click="exportHistory">导出</span>
          </div>
          <Line :data="historyChartData" :x-data="xData"></Line>
        </div>
      </div>
      <div class="right">
        <div class="top">
          <Title :title="'集热管失真空'" @click="handleClickUpdate"></Title>
          <SingleBar :data="chartData4"></SingleBar>
        </div>
        <div class="middle">
          <Title :title="'集热管弯曲'"></Title>
          <SingleBar :data="chartData5"></SingleBar>
        </div>
        <div class="bottom">
          <Title :title="'集热管变形'"></Title>
          <SingleBar :data="chartData6"></SingleBar>
        </div>
      </div>
    </div>
    <!--    <OverviewMap v-if="showPopup" @close-popup="closePopup"></OverviewMap>-->
    <BulletFrame v-if="showPopup" @close-popup="closePopup"></BulletFrame>
  </div>
</template>
<script setup>
import { nextTick, onMounted, ref, shallowRef, watch, provide } from 'vue'
import Header from '../../components/Header.vue'
import Title from '../../components/Title.vue'
import Line from './Components/Line.vue'
// import OverviewMap from './Components/OverviewMap.vue'
import BulletFrame from './Components/BulletFrame.vue'
import SingleBar from './Components/SingleBar.vue'
import StatisticsData from './Components/StatisticsData.vue'
import videoUrl1 from '/src/assets/file/video.mp4'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import dayjs from 'dayjs'
import { getTotalData, getChainData, getHistoryData } from '../../api/common/home'
// 用于点击中间区域的事件
const message = ref('')
provide('sharedMessage', message)
const showPopup = ref(false)
const chartData1 = ref()
const chartData2 = ref()
const chartData3 = ref()
const chartData4 = ref()
const chartData5 = ref()
const chartData6 = ref()
// 播放视频路径
let videoUrl = ref(videoUrl1)
// 导出左右使用数据
const exportChartData = ref()
// 中间区域静态展示数据
const StatisticDatas = ref()
// 历史曲线
let chooseMonth = ref([
  dayjs().subtract(2, 'month').format('YYYY-MM'),
  dayjs(new Date()).format('YYYY-MM')
])
let historyTitle = []
let historyChartData = ref([
  { name: '集热管破损', data: [0] },
  { name: '外镜破损', data: [0] },
  { name: '内镜破损', data: [0] },
  { name: '集热管失真空', data: [0] },
  { name: '集热管弯曲', data: [0] },
  { name: '集热管变形', data: [0] }
])

let xData = ref([])
// 导出历史曲线组装数据
let exportHistoryDatas = []
// 日期禁止选择
function disabledDate(time) {
  return time.getTime() > Date.now()
}

function handleClick() {
  showPopup.value = true
}
function handleClickUpdate() {
  // autoUpdater.checkForUpdates()
}

function closePopup() {
  showPopup.value = false
}
// 月份改变发起请求，刷新左右数据
function handleUpdate(val) {
  getChainData(val).then((res) => {
    if (res.code === 200) {
      let data = res.data
      let now = data.result_now
      let before = data.before_data

      chartData1.value = {
        name: '集热管破损',
        data: [before['Broken collector tubes'] || 0, now['Broken collector tubes'] || 0]
      }
      chartData2.value = {
        name: '外镜破损',
        data: [before['Broken external mirror'] || 0, now['Broken external mirror'] || 0]
      }
      chartData3.value = {
        name: '内镜破损',
        data: [before['Broken inner mirror'] || 0, now['Broken inner mirror'] || 0]
      }
      chartData4.value = {
        name: '集热管失真空',
        data: [before['Loss of vacuum'] || 0, now['Loss of vacuum'] || 0]
      }
      chartData5.value = { name: '集热管弯曲', data: [0, 0] }
      chartData6.value = { name: '集热管变形', data: [0, 0] }

      exportChartData.value = [
        chartData1.value,
        chartData2.value,
        chartData3.value,
        chartData4.value,
        chartData5.value,
        chartData6.value
      ]
      StatisticDatas.value = [
        chartData1.value.data[1],
        chartData2.value.data[1],
        chartData3.value.data[1],
        chartData4.value.data[1],
        chartData5.value.data[1],
        chartData6.value.data[1]
      ]
    }
  })
}

function handleUpdateVideo(value) {
  videoUrl.value = value
}

function reset() {
  chartData1.value = { name: '集热管破损', data: [0, 0] }
  chartData2.value = { name: '外镜破损', data: [0, 0] }
  chartData3.value = { name: '内镜破损', data: [0, 0] }
  chartData4.value = { name: '集热管失真空', data: [0, 0] }
  chartData5.value = { name: '集热管弯曲', data: [0, 0] }
  chartData6.value = { name: '集热管变形', data: [0, 0] }
  exportChartData.value = [
    chartData1.value,
    chartData2.value,
    chartData3.value,
    chartData4.value,
    chartData5.value,
    chartData6.value
  ]
  StatisticDatas.value = [
    chartData1.value.data[1],
    chartData2.value.data[1],
    chartData3.value.data[1],
    chartData4.value.data[1],
    chartData5.value.data[1],
    chartData6.value.data[1]
  ]
}

// 历史曲线月份改变
function historyChange(val) {
  getAreaMonth(val[0], val[1])
}
function getAreaMonth(start, end) {
  const months = []
  let current = dayjs(start)
  const stop = dayjs(end)
  // 组装日期参数
  const param = [current.format('YYYY-MM'), stop.format('YYYY-MM')]
  while (current.isBefore(stop) || current.isSame(stop, 'month')) {
    months.push(current.format('YYYY-MM')) // 或者 'YYYY-MMM' 格式化为你需要的形式
    current = current.add(1, 'month') // 移动到下一个月
  }

  // 重置
  historyChartData.value = [
    { name: '集热管破损', data: [0] },
    { name: '外镜破损', data: [0] },
    { name: '内镜破损', data: [0] },
    { name: '集热管失真空', data: [0] },
    { name: '集热管弯曲', data: [0] },
    { name: '集热管变形', data: [0] }
  ]

  const nameMapping = {
    'Loss of vacuum': '集热管失真空',
    'Broken inner mirror': '内镜破损',
    'Broken collector tubes': '集热管破损',
    'Broken external mirror': '外镜破损',
    a: '集热管弯曲',
    b: '集热管变形'
  }

  getHistoryData(param).then((res) => {
    if (res.code === 200) {
      let _data = res.data

      const allNames = new Set(Object.keys(nameMapping))

      // 2. 为每个故障类型生成数据数组，并转换为中文
      const result = Array.from(allNames).map((englishName) => {
        const data = months.map((month) => {
          return _data[month]?.[englishName] || 0 // 取对应月份的值，若无则填 0
        })
        return {
          name: nameMapping[englishName], // 直接映射为中文
          data
        }
      })
      historyChartData.value = result
      xData.value = months
      historyTitle = ['类型', ...months]
    }
  })
}
// 历史曲线导出
function exportHistory() {
  let resData = []
  historyChartData.value.forEach((item, index) => {
    resData[index] = []
    item.data.forEach((it) => {
      resData[index].push(it)
    })
    resData[index].unshift(item.name)
  })
  exportHistoryDatas.value = resData
  // 定义数据
  // let datas = [
  //   ['类型', '当月', '上月']
  //   // 更多数据...
  // ]
  const data = [historyTitle, ...exportHistoryDatas.value]
  console.log(data)
  // 将数据转换为工作表
  const ws = XLSX.utils.aoa_to_sheet(data)

  // 创建工作簿并添加工作表
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 生成Excel文件并导出
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })

  // 使用file-saver保存文件
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
  saveAs(
    blob,
    dayjs(chooseMonth.value[0]).format('YYYY年MM月') +
      '至' +
      dayjs(chooseMonth.value[1]).format('YYYY年MM月') +
      '数据导出.xlsx'
  )
}
function s2ab(s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
  return buf
}
onMounted(() => {
  nextTick(() => {
    handleUpdate(dayjs(new Date()).format('YYYY-MM'))
    getAreaMonth(chooseMonth.value[0], chooseMonth.value[1])
  })
})
</script>
<style scoped lang="scss">
.home {
  width: 19.2rem;
  height: 10.8rem;
  margin: 0 auto;
}
.homeMain {
  margin: 0.36rem 0.3rem 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 9.5rem;
  .left,
  .right,
  .center {
    height: 9.5rem;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  .left,
  .right {
    width: 3.86rem;
    > div {
      height: 3.1rem;
      padding-top: 0.16rem;
      position: relative;
    }
  }
  .center {
    width: 9.3rem;
    .centerBox {
      height: 6.3rem;
      background: url('../../assets/images/home/bg-ditu.png') no-repeat;
      background-size: 100% 100%;
    }
    .centerVideo {
      height: 4.8rem;
      margin-top: 0.14rem;
    }
    .statistics {
      height: 1.3rem;
      cursor: pointer;
    }
    .centerBottom {
      height: 3.1rem;
      padding-top: 0.16rem;
      position: relative;
    }
    .historyMonths {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 0.16rem;
      width: 3rem;
      display: flex;
      justify-content: space-between;
      > span {
        width: 0.8rem;
        margin-left: 0.2rem;
        height: 0.28rem;
        line-height: 0.28rem;
        font-size: 0.16rem;
        color: #02d9ff;
        cursor: pointer;
        border: 0.8px solid #02d9ff;
        background: linear-gradient(
          -180deg,
          rgba(5, 238, 255, 0.05) 0%,
          rgba(2, 217, 255, 0.3) 100%
        );
      }
      :deep(.el-input) {
        height: 0.28rem;
        width: 1.74rem;
      }
      :deep(.el-input__wrapper) {
        height: 0.28rem;
        box-shadow: none;
        border: 0.8px solid #02d9ff;
        background: linear-gradient(
          -180deg,
          rgba(5, 238, 255, 0.05) 0%,
          rgba(2, 217, 255, 0.3) 100%
        );
      }
      :deep(.el-range-input),
      :deep(.el-range-separator),
      :deep(.el-input__icon) {
        font-size: 0.16rem;
        color: #02d9ff;
      }
    }
  }
}
</style>
